package com.lu.common.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Properties;
import java.util.Random;

public class SendEmailUtil {

    public int sendEmail(String reperson)

    {
        int result = 0;
        // 收件人电子邮箱
        String to = reperson;

        // 发件人电子邮箱
        String from = "showluu@163.com";

        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.163.com";  //163邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");


        //阿里云服务器禁用25端口，所以服务器上改为465端口
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.port", "465");


        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("showluu@163.com", "showlu19970108xx"); //发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // Set Subject: 头部头字段
            message.setSubject("注册论坛网验证码");

            // 设置消息体
            Random rand = new Random();
            String txt = String.valueOf(rand.nextInt(9000) + 1000);
            message.setText("你好" + reperson + "!  欢迎注册论坛网。验证码为:" + txt);

            // 发送消息
            Transport.send(message);

            result = 1;
        } catch (MessagingException mex) {
            mex.printStackTrace();
            System.out.println(mex.toString());
        }
        return result;
    }

    public static void main(String[] args) {
        new SendEmailUtil().sendEmail("1309617271@qq.com");
    }

}
